function keySetup (key) {
  var S = []
  for (var i = 0; i < 256; i++) {
    S[i] = i
  }

  var j = 0
  for (var i = 0; i < 256; i++) {
    j = (j + S[i] + key.charCodeAt(i % key.length)) % 256;
    [S[i], S[j]] = [S[j], S[i]] // ES6 swap
  }
  return S
}

function rc4 (key, text) {
  var S = keySetup(key)
  var i = 0
  var j = 0
  var result = []
  for (var y = 0; y < text.length; y++) {
    i = (i + 1) % 256
    j = (j + S[i]) % 256;
    [S[i], S[j]] = [S[j], S[i]] // ES6 swap
    var R = S[(S[i] + S[j]) % 256]
    result.push(text.charCodeAt(y) ^ R)
  }
  return result
}

function byteArrayToHex (byteArray) {
  let hexString = ''
  for (let i = 0; i < byteArray.length; i++) {
    let hex = byteArray[i].toString(16)
    if (hex.length < 2) {
      hex = '0' + hex
    }
    hexString += hex
  }
  return hexString
}

export default {
  rc4,
  byteArrayToHex
}